<?php

class CouponController extends BaseController
{
    private $req;

    public function init()
    {
        $this->req = $this->getRequest();
        if ($this->req->isXMLHttpRequest()) {
            Zend_Controller_Action_HelperBroker::getStaticHelper('viewRenderer')->setNoRender(true);
            $layout = Zend_Layout::getMvcInstance();
            if ($layout instanceof Zend_Layout) {
                $layout->disableLayout();
            }
        }
        $this->view->breadcrumb = array(array(
            'url' => '/winning/index',
            'name' => '优惠券',
        ));
    }

    public function indexAction()
    {
        $player_list = new \Orm\Coupon\CouponList();
        $size = Page::ValidatePageSize($this->req->get('pageSize'), '/coupon/index'); //每页显示条数
        $now = $this->req->get('p') ? $this->req->get('p') : 1;//当前页数
        $where = '';
        $player_list['where'] = $where;
        $player_list['limit'] = $size;
        $player_list['offset'] = ($now - 1) * $size;
        $player_list['order'] = '`insert_time` desc';
        $player_list['key_by'] = 'id';
        $player_list->load();
        $page = new Page($player_list['total'], $size, $now, '/coupon/index?', 2);
        $this->view->size = $size;
        $this->view->now = $now;
        $this->view->pageStr = $page->showPage();
        $this->view->list_result = $player_list['lists'];
        $this->view->breadcrumb = array(
            array(
                'name' => '优惠券列表',
            ));
    }

    public function typeAction()
    {
        $player_list = new \Orm\CouponType\CouponTypeList();
        $size = Page::ValidatePageSize($this->req->get('pageSize'), '/coupon/type'); //每页显示条数
        $now = $this->req->get('p') ? $this->req->get('p') : 1;//当前页数
        $where = '';
        $player_list['where'] = $where;
        $player_list['limit'] = $size;
        $player_list['offset'] = ($now - 1) * $size;
        $player_list['order'] = '`insert_time` desc';
        $player_list['key_by'] = 'id';
        $player_list->load();
        $page = new Page($player_list['total'], $size, $now, '/coupon/type?', 2);
        $this->view->size = $size;
        $this->view->now = $now;
        $this->view->pageStr = $page->showPage();
        $this->view->list_result = $player_list['lists'];
        $this->view->breadcrumb = array(
            array(
                'name' => '优惠券分类',
            ));
    }
    public function excelAction()
    {
        // action body
        if (!isset($_FILES['inputExcel'])) {
            return Response::Error(0, '请选择上传Excel文件');
        }
        // 更换文件保存的位置
        $filepath = $this->uploadExcel($this->user_id);

        // 操作表
        $filename = $_FILES['inputExcel']['name'];
        $code_res = $this->readExcel($filename, $filepath);
        if (is_array($code_res)) {
            $coupon = new \Biz\Coupon();
            $res = $coupon->verificationCoupon($code_res);
            if ($res) {
                return Response::Success('', 'success');
            }else{
                return Response::Error('', "核销失败");
            }
        } else {
            return Response::Error('', "核销失败");
        }


    }
    private function uploadExcel($user_id)
    {
        $upfile = $_FILES["inputExcel"];
        //$name = $user_id . '_' . iconv('utf-8', 'gb2312', $upfile["name"]); //上传文件的文件名
        $name = $user_id . '_' . $upfile["name"];//上传文件的文件名
        $type = $upfile["type"]; //上传文件的类型
        $size = $upfile["size"]; //上传文件的大小
        $tmp_name = $upfile["tmp_name"]; //上传文件的临时存放路径
        // $auth = new Application_Model_Auth();
        // $name_uid = $auth ->getUserId();
        $name_uid = "verificationExcel";
        if (!file_exists($name_uid)) {
            mkdir($name_uid, 0700);
        }
        $filepath = $name_uid . '/' . $name;
        move_uploaded_file($tmp_name, $filepath);
        return $filepath;
    }
    private function readExcel($filename, $file_path)
    {
        error_reporting(E_ALL);
        ini_set("display_errors", 0);
        require_once 'excel/PHPExcel.php';
        header('Content-Type: text/html; charset=utf-8');
        //$objReader = PHPExcel_IOFactory::createReaderForFile($filename);
        $objPHPExcel = PHPExcel_IOFactory::load($file_path);
        $sheetNames = $objPHPExcel->getSheetNames();
        if (!in_array('Sheet1', $sheetNames)) {
            return "保存excel工作表明必须为Sheet1";
        }

        // 操作Sheet1
        $objPHPExcel->setActiveSheetIndexByName('Sheet1');
        $objWorksheet = $objPHPExcel->getActiveSheet();

        if ($objWorksheet->getHighestRow() < 2) {
            return "该表没有任何记录！请检查！";
        }

        $arr = array();
        foreach ($objWorksheet->getRowIterator() as $k => $row) {
            $cellIterator = $row->getCellIterator();
            $cellIterator->setIterateOnlyExistingCells(false);
            foreach ($cellIterator as $cell) {
                $arr[$k][] = (string)$cell->getValue();
            }
        }
        return $arr;
    }
}